package com.openroom.ui.component;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.apache.pivot.collections.Map;
import org.apache.pivot.serialization.SerializationException;
import org.apache.pivot.util.Resources;
import org.apache.pivot.wtk.Border;
import org.apache.pivot.wtk.BoxPane;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtk.ComponentMouseButtonListener;
import org.apache.pivot.wtk.ComponentMouseListener;
import org.apache.pivot.wtk.Cursor;
import org.apache.pivot.wtk.Label;
import org.apache.pivot.wtk.Mouse.Button;
import org.apache.pivot.wtk.media.Picture;

import com.jphotomanager.io.ImageLibrary;
import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.ModelLocator;
import com.openroom.model.ModelLocator.ModeFlag.SelectMode;
import com.openroom.model.Photograph;
import com.openroom.ui.FocusableImageView;

public class ThumbnailView extends Border {

    private static final Logger LOGGER = Logger.getLogger(ThumbnailView.class);
    public static int imageCounter = 1;
    protected Label label;
    protected FocusableImageView imageView;

    protected Photograph image;

    protected boolean hidden = false;

    public ThumbnailView() {
    }

    public void initialize(Map<String, Object> namespace, URL arg1,
            Resources arg2) {
        setCursor(Cursor.HAND);
        final BoxPane box = (BoxPane) namespace.get("box");
        imageView = (FocusableImageView) namespace.get("tnail");
        label = (Label) namespace.get("imageCounter");
        label.setText(imageCounter++ + "/"
                + ModelLocator.getInstance().getAllPhotographsOfFolder().size());
        imageView.setCursor(Cursor.HAND);

        addListeners(box);
    }

    protected void addListeners(final BoxPane box) {
        EventManager.getInstance().listenToEventType(
                EventType.CURRENT_IMAGE_CHANGED, new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        if (ModelLocator.getInstance().getCurrentSelectMode()
                                .equals(SelectMode.SINGLE)) {
                            Photograph currentlySelectedImage = ModelLocator
                                    .getInstance().getCurrentlySelectedImage();
                            if (currentlySelectedImage != null
                                    && currentlySelectedImage.getPhotoId() != image
                                            .getPhotoId()) {
                                try {
                                    box.setStyles("{backgroundColor:'#808080'}");
                                    setStyles("{backgroundColor:'#808080'}");
                                } catch (SerializationException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });

        imageView.getComponentMouseButtonListeners().add(
                new ComponentMouseButtonListener() {

                    @Override
                    public boolean mouseDown(Component component,
                            Button button, int x, int y) {
                        return false;
                    }

                    @Override
                    public boolean mouseUp(Component component, Button button,
                            int x, int y) {
                        return false;
                    }

                    @Override
                    public boolean mouseClick(Component component,
                            Button button, int x, int y, int count) {
                        if (ModelLocator.getInstance().getCurrentSelectMode()
                                .equals(SelectMode.SINGLE)) {
                            ModelLocator.getInstance()
                                    .setCurrentlySelectedImage(image);
                        }
                        return false;
                    }
                });
        getComponentMouseButtonListeners().add(
                new ComponentMouseButtonListener() {

                    @Override
                    public boolean mouseDown(Component component,
                            Button button, int x, int y) {
                        return false;
                    }

                    @Override
                    public boolean mouseUp(Component component, Button button,
                            int x, int y) {
                        return false;
                    }

                    @Override
                    public boolean mouseClick(Component component,
                            Button button, int x, int y, int count) {
                        Border border = (Border) component;
                        try {
                            box.setStyles("{backgroundColor:'#bebebe'}");
                            border.setStyles("{backgroundColor:'#bebebe'}");
                        } catch (SerializationException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }
                });
        getComponentMouseListeners().add(new ComponentMouseListener() {

            @Override
            public boolean mouseMove(Component component, int x, int y) {
                return false;
            }

            @Override
            public void mouseOver(Component component) {
                Border border = (Border) component;
                try {
                    box.setStyles("{backgroundColor:'#bebebe'}");
                    border.setStyles("{backgroundColor:'#bebebe'}");
                } catch (SerializationException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void mouseOut(Component component) {
                if (ModelLocator.getInstance().getCurrentSelectMode()
                        .equals(SelectMode.SINGLE)) {
                    Photograph currentlySelectedImage = ModelLocator
                            .getInstance().getCurrentlySelectedImage();
                    if (currentlySelectedImage != null
                            && currentlySelectedImage.getPhotoId() != image
                                    .getPhotoId()) {
                        try {
                            box.setStyles("{backgroundColor:'#808080'}");
                            setStyles("{backgroundColor:'#808080'}");
                        } catch (SerializationException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (!ModelLocator.getInstance().getMultiSelectedImages()
                            .contains(image)) {
                        try {
                            box.setStyles("{backgroundColor:'#808080'}");
                            setStyles("{backgroundColor:'#808080'}");
                        } catch (SerializationException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        });
    }

    public void hide() {
        hidden = true;
        this.setVisible(false);
    }

    public boolean isHidden() {
        return hidden;
    }

    public void setCounter(int newCounter) {
        label.setText(newCounter + "/"
                + ModelLocator.getInstance().getAllPhotographsOfFolder().size());
    }
    
    public void setCounter(int newCounter,int length) {
        label.setText(newCounter + "/"
                + length);
    }


    public void setImage(final Photograph image) {
        if (isHidden()) {
            this.setVisible(true);
            hidden = false;
        }
        this.image = image;
        try {
            ImageLibrary.getInstance().getExecutorService()
                    .submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                imageView.setImage(new Picture(ImageIO
                                        .read(new File(image.getThumbnailPath()))));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

        } catch (Exception e) {
            LOGGER.error("Can not load " + image.getThumbnailPath());
        }
        imageView.getUserData().put(FocusableImageView.IMAGE_DATA_KEY, image);
    }

}
